package service

import (
	"context"
	"fmt"
	"strings"
	"time"

	jsoniter "github.com/json-iterator/go"
	"zhonghui/console/structs"
	"zhonghui/console/warehouse/cfgx"
	"zhonghui/console/warehouse/dbx/cache_main"
	"zhonghui/console/warehouse/envx"
	"zhonghui/console/warehouse/modelx/model_zh_kernel"
	"zhonghui/console/warehouse/mqx"
)

// TriggerFileParseTask 触发一个任务的文件解析
func TriggerFileParseTask(taskID uint64) error {
	p, err := mqx.NewNsqProducer()
	if err != nil {
		return err
	}

	body := structs.FileParseWorkerBody{TaskID: taskID}
	j, _ := jsoniter.Marshal(body)

	return p.Publish(cfgx.Cfg().GetString("console.topics.file_parse"), j)
}

// TriggerSmsSendTask 触发一个任务的短信发送
func TriggerSmsSendTask(taskID, recordID uint64) error {
	p, err := mqx.NewNsqProducer()
	if err != nil {
		return err
	}

	body := structs.SmsSendWorkerBody{TaskID: taskID, RecordID: recordID}
	j, _ := jsoniter.Marshal(body)

	return p.Publish(cfgx.Cfg().GetString("console.topics.sms_send"), j)
}

// TriggerSmsSendTaskMulti 触发多个任务的短信发送
func TriggerSmsSendTaskMulti(req []structs.SmsSendWorkerBody) error {
	p, err := mqx.NewNsqProducer()
	if err != nil {
		return err
	}

	j := make([][]byte, 0)
	for _, d := range req {
		t, _ := jsoniter.Marshal(d)
		j = append(j, t)
	}

	return p.MultiPublish(cfgx.Cfg().GetString("console.topics.sms_send"), j)
}

// IsSafeTimeForTask 推广短信发送时间为每日8:00 - 21:00，夜间无法发送，避免用户投诉。
func IsSafeTimeForTask() bool {
	return true
	if !envx.InProd() {
		return true
	}
	return time.Now().Hour() >= 8 && time.Now().Hour() < 21
}

// ParseRecordParamsForSms 取出记录中的模板变量信息，再取出短网址信息，拼接成完整的短信模板变量
func ParseRecordParamsForSms(record *model_zh_kernel.SysSmsRecord) []string {
	resp := make([]string, 0)
	jsoniter.UnmarshalFromString(record.Params, &resp)
	if record.Dwz != "NONE" {
		a := strings.ReplaceAll(record.Dwz, "dwz.cn/", "")
		a = strings.ReplaceAll(a, "j.pubmi.cn/d/", "")
		resp = append(resp, a)
	}
	return resp
}

// GetTaskTempProgress 获取任务进行中的时候，缓存中的发送进度
func GetTaskTempProgress(taskId uint64) uint64 {
	key := fmt.Sprintf(structs.TaskTempProgressKey, taskId)
	res, _ := cache_main.Client().Get(context.Background(), key).Int()
	return uint64(res)
}

// AddTaskTempProgress 任务进行中的时候，增加缓存中的发送进度
func AddTaskTempProgress(taskId uint64) uint64 {
	key := fmt.Sprintf(structs.TaskTempProgressKey, taskId)
	res := cache_main.Client().Incr(context.Background(), key).Val()
	return uint64(res)
}

// GetTaskTempProgressFail 获取任务进行中的时候，缓存中的发送进度
func GetTaskTempProgressFail(taskId uint64) uint64 {
	key := fmt.Sprintf(structs.TaskTempProgressFailKey, taskId)
	res, _ := cache_main.Client().Get(context.Background(), key).Int()
	return uint64(res)
}

// AddTaskTempProgressFail 任务进行中的时候，增加缓存中的发送进度
func AddTaskTempProgressFail(taskId uint64) uint64 {
	key := fmt.Sprintf(structs.TaskTempProgressFailKey, taskId)
	res := cache_main.Client().Incr(context.Background(), key).Val()
	return uint64(res)
}
